package service

var (
	codeToIPPort map[string]string
	iPPortToCode map[string]string
)

func init() {
	codeToIPPort = make(map[string]string)
	iPPortToCode = make(map[string]string)
}

//description: 查看是否已经登录, 但是登录不代表合法，需要配合IsWinLinkValid使用
//param {string} ip
//param {string} port
//return {*}

func IsWinLinkLogined(ip string, port string) bool {
	_, ok := iPPortToCode[ip+":"+port]
	return ok
}

func IsCmdCodeValid(code string) bool {
	_, ok := codeToIPPort[code]

	return ok
}

//description: 查看code是否和IP和Port配对，以此来校验合法性
//param {string} ip
//param {string} port
//param {string} code
//return {*}

func IsWinLinkValid(ip string, port string, code string) bool {
	if !IsWinLinkLogined(ip, port) {
		return false
	}

	storedCode := iPPortToCode[ip+":"+port]
	return code == storedCode
}

func WinLinkLoggin(ip string, port string) string {
	code := GetGuidForLink()
	iPPortToCode[ip+":"+port] = code
	codeToIPPort[code] = ip + ":" + port

	return code
}

func WinLinkLoggout(ip string, port string) {
	code, ok := iPPortToCode[ip+":"+port]
	if ok {
		delete(codeToIPPort, code)
	}
	delete(iPPortToCode, ip+":"+port)
}

func GetLinkedWinLinkCode(ip string, port string) string {
	code := iPPortToCode[ip+":"+port]

	return code
}

func GetWinLinIPPortByCode(code string) (string, bool) {
	ipPort, ok := codeToIPPort[code]
	if !ok {
		return "", false
	}

	return ipPort, true
}
